package org.john.springbootadmin.module.service.system.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.john.springbootadmin.module.bean.vo.SysPermissionVo;
import org.john.springbootadmin.module.dao.system.SysPermissionDao;
import org.john.springbootadmin.module.entity.system.SysPermission;
import org.john.springbootadmin.module.service.system.SysPermissionService;
import org.springframework.stereotype.Service;

import com.design.framework.base.service.impl.BaseServiceImpl;
import com.design.framework.tree.TreeNode;
import com.design.framework.utils.TokenUtils;

/**
 * 系统权限管理
 * 
 * @author johnDeng
 * @dateTime 2019-03-18 02:12:58
 */
@Service
public class SysPermissionServiceImpl extends BaseServiceImpl<SysPermission, Integer> implements SysPermissionService {
	@Resource
	private SysPermissionDao sysPermissionDao;

	@PostConstruct
	public void initialize() {
		super.setBaseDao(sysPermissionDao);
	}

	@Override
	public List<TreeNode<Integer>> getMenuTree() {
		List<SysPermission> list = sysPermissionDao.getListMenuByUserId(Integer.valueOf(TokenUtils.getUserId(request)));
		if (CollectionUtils.isNotEmpty(list)){
			return getTree("id", "parentId", 0, new SysPermission(), list);
		} else{
			return null;
		}

	}

	/**
	 * 权限实体转树节点
	 */
	@Override
	public TreeNode<Integer> entityToTreeNode(TreeNode<Integer> node, SysPermission entity) {
		SysPermissionVo<Integer> sysPermissionVo = new SysPermissionVo<Integer>();
		sysPermissionVo.setId(entity.getId());
		sysPermissionVo.setParentId(entity.getParentId());
		sysPermissionVo.setName(entity.getName());
		sysPermissionVo.setUrl(entity.getUrl());
		sysPermissionVo.setChecked(true);
		sysPermissionVo.setDisabled(true);
		sysPermissionVo.setPermission(entity.getPermission());
		sysPermissionVo.setType(entity.getType());
		sysPermissionVo.setGrade(entity.getGrade());
		sysPermissionVo.setIcon(entity.getImageUrl());
		return sysPermissionVo;
	}

	@Override
	public Map<String, Object> getAllTreeByRoleId(Integer roleId) {
		List<SysPermission> allList = sysPermissionDao.findAll();
		Integer[] ids = listToArrayId(sysPermissionDao.getListPermissionByRoleId(roleId));
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put("list", allList);
		map.put("checkedId", ids);
		return map;
	}

	private Integer[] listToArrayId(List<SysPermission> list) {
		Integer[] ids = {};
		if (CollectionUtils.isNotEmpty(list)) {
			ids = new Integer[list.size()];
			for (int i = 0; i < list.size(); i++) {
				ids[i] = list.get(i).getId();
			}
		}
		return ids;
	}

	@Override
	public List<TreeNode<Integer>> getAllTree() {
		return getTree("id", "parentId", 0, new SysPermission(), findAll());
	}

	@Override
	public List<SysPermission> getChildrenByParentId(Integer parentId) {
		return sysPermissionDao.getChildrenByParentId(parentId);
	}
	

}
